package com.hmdp.utils;

import org.springframework.cglib.core.Local;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    /*
     *   当前年的开始时间戳
     *   System.out.println(LocalDateTime.of(2024,1,1,0,0,0).toEpochSecond(ZoneOffset.UTC));
     *
     * */
    private static final Long NOW_TIME = 1704067200L;
    /*
     *   序列号的位数
     *
     * */
    private static final int COUNT_BITS = 32;
    private final StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public  Long nextId(String keyPrefix) {
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - NOW_TIME;
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        if (keyPrefix == null) {
            return -1L;
        }
        /*
        *
        *   设置id自增的算法
        *
        * */
        long current = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + data);
        /*
        *   高位补充
        *
        * */
        return timeStamp << COUNT_BITS | current;
    }
}
